<template>
  <div class="bg">
    <div class="welcome">欢迎注册</div>
    <div class="desc">卡密绑定注册登录即可兑换更多优惠福利</div>
    <div class="loginForm">
      <div class="loginForm-item">
        <header>注册</header>
        <div @click="scanQRCode">
          <img src="../assets/login/code.svg" alt="">
          <span>扫一扫</span>
        </div>
      </div>
      <van-form @submit="onSubmit">
        <van-field class="cell-wrap" v-model="cardNo" name="cardNo" show-error="false" placeholder="请输入卡号"
          :rules="[{ required: true, message: '请输入卡号' }]">
          <template #left-icon>
            <img src="../assets/register/number.svg" style="width: 13px; height: 18px; margin-right: 3px;" />
          </template>
        </van-field>
        <van-field class="cell-wrap" show-error="false" v-model="cardPwd" name="cardPwd" placeholder="请输入卡密"
          :rules="[{ required: true, message: '请输入卡密' }]">
          <template #left-icon>
            <img src="../assets/register/password.svg" style="width: 13px; height: 18px; margin-right: 3px;" />
          </template>
        </van-field>
        <van-field class="cell-wrap" show-error="false" v-model="phonenumber" name="phonenumber" placeholder="请输入手机号"
          :rules="[{ required: true, message: '请输入手机号' }]">
          <template #left-icon>
            <img src="../assets/login/phone.svg" style="width: 13px; height: 18px; margin-right: 3px;" />
          </template>
          <template #button>
            <div class="code" @click="getCode" :class="{ disabled: countdown > 0 }">
              {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
            </div>
          </template>
        </van-field>
        <van-field class="cell-wrap cell-wrap2" show-error="false" left-icon="smile-o" v-model="code" name="code"
          placeholder="请输入验证码" :rules="[{ required: true, message: '请输入验证码' }]">
          <template #left-icon>
            <img src="../assets/login/codeC.svg" style="width: 13px; height: 14px; margin-right: 3px;" />
          </template>
        </van-field>
        <van-field class="cell-wrap-copy" name="checkbox">
          <template #input>
            <van-checkbox v-model="agree" icon-size="12px" />
            <div class="agree">
              <span>我已阅读并同意</span>
              <span @click="goconfiguration(1)">《用户协议》</span>
              <span @click="goconfiguration(2)">《隐私政策》</span>
            </div>
          </template>
        </van-field>
        <div style="margin: 41px 0 0 0;">
          <van-button round block type="info" native-type="submit">注册</van-button>
        </div>
      </van-form>
      <div class="gore" @click="goLogin"><span>已有账号，去登录</span></div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.bg {
  width: 375px;
  height: 458px;
  background: linear-gradient(131deg, rgba(252, 151, 144, 0.3) 0%, rgba(255, 221, 254, 0.2) 52%, rgba(255, 206, 218, 0.84) 83%, #FFFFFF 100%);
  border-radius: 0px;

  .loginForm {
    width: calc(100% - 22px);
    height: 485px;
    margin: auto;
    background-image: url("../assets/login/bg.png");
    background-repeat: no-repeat;
    background-position: center center;
    background-size: 100% 485px;

    .loginForm-item {
      width: 100%;
      height: 40px;
      display: flex;

      header {
        width: calc(100% - 120px);
        height: 40px;
        text-align: center;
        line-height: 40px;
        font-family: DingTalk JinBuTi;
        font-weight: 400;
        font-size: 20px;
        color: #EE473B;
        // padding-top: 10px;
        box-sizing: border-box;
      }

      >div {
        width: 120px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;

        >img {
          width: 20px;
          height: 20px;
          margin-right: 5px;
        }

        >span {
          font-family: DingTalk JinBuTi;
          font-weight: 400;
          font-size: 14px;
          color: #FFFFFF;
        }
      }
    }

    .van-form {
      width: calc(100% - 36px);
      margin: 30px auto 0;
    }

    .cell-wrap {
      width: 100%;
      background: #F8F8F8;
      border-radius: 23px;
      margin-bottom: 12px;
      padding: 13px 23px;
      box-sizing: border-box;
      overflow: inherit;
    }

    .cell-wrap2 {
      //margin-bottom: 2px;
    }

    ::v-deep .van-field__error-message {
      margin-top: 3px;
      font-size: 10px;
    }

    .code {
      padding: 0 0 0 10px;
      border-left: 1px solid #D3D3D3;
      font-family: PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #EE473B;

    }

    .van-cell::after {
      display: none;
    }

    ::v-deep .van-field__left-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      padding-right: 10px;
    }

    .cell-wrap-copy {
      height: auto;
      padding: 0 23px;
      margin-top: 10px;
      overflow: visible; // 确保内容不被裁剪

      ::v-deep .van-checkbox {
        flex-shrink: 0; // 防止被压缩
        margin-right: 8px; // Add space between checkbox and text
      }

      .agree {
        width: 100%;

        span {
          font-size: 12px;
        }

        span:nth-child(1) {
          color: #9B9B9B;
        }

        span:nth-child(2) {
          color: #EE473B;
        }

        span:nth-child(3) {
          color: #EE473B;
        }
      }
    }

    .van-button {
      background: linear-gradient(103deg, #F49E97 0%, #EE473B 100%);
      box-shadow: 0px 3px 6px rgba(238, 71, 59, 0.2);
      border-radius: 23px;
      border: none;
      height: 46px;
      width: 100%;
      font-weight: 400;
      font-size: 16px;
      color: #FFFFFF;
    }

    .gore {
      width: 100%;
      text-align: center;
      font-weight: 400;
      font-size: 14px;
      color: #EE473B;
      margin-top: 17px;
    }
  }

  .desc {
    height: 20px;
    font-family: PingFang SC;
    font-size: 14px;
    padding-top: 5px;
    color: #A2A2A2;
    padding-left: 33px;
    padding-bottom: 30px;
    margin-top: 5px;
  }

  .welcome {
    padding-top: 86px;
    padding-left: 33px;
    // width: 161px;
    height: 36px;
    font-family: DingTalk JinBuTi;
    font-size: 30px;
    color: #EE473B;
  }
}
</style>
<script>
import plantAPI from "@/api/plant";
import loginAPI from "@/api/login";
import { Toast } from 'vant';
import wx from "weixin-js-sdk";
export default {
  data() {
    return {
      scanResult: '',
      loading: false,
      countdown: 0, // 倒计时秒数
      timer: null,// 定时器
      phonenumber: '',
      cardPwd: '',
      cardNo: '',
      code: '',
      agree: false,
      wxConfigCompleted: false, // 新增：标识微信配置是否完成
    }
  },
  beforeUnmount() {
    // 组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  created() {
    this.cardNo = localStorage.getItem("cardNo") ? localStorage.getItem("cardNo") : ''
    this.cardPwd = localStorage.getItem("cardPwd") ? localStorage.getItem("cardPwd") : ''
    localStorage.removeItem("cardNo")
    localStorage.removeItem("cardPwd")
  },
  mounted() {
    this.handleWechatCallback();
    this.getWxConfig();
    //    this.initWxSDK().then(() => {
    //   this.handleWechatCallback();
    // });
  },
  methods: {
    goconfiguration(type) {
      if (type == 1) {
        this.$router.push({
          path: '/aboutMine'
        })
      } else {
        this.$router.push({
          path: '/policy'
        })
      }
    },
    scanQRCode() {
      if (!wx.scanQRCode) {
        Toast.fail("当前环境不支持扫一扫");
        return;
      }
      wx.ready(() => {
        wx.scanQRCode({
          needResult: 1,
          scanType: ["qrCode", "barCode"],
          success: (res) => {
            const url = new URL(res.resultStr);
            this.cardNo = url.searchParams.get('cardNo') || '';
            this.cardPwd = url.searchParams.get('cardPwd') || '';
          },
          fail: (err) => {
            console.error('扫描失败:', err.errMsg);
            Toast.fail('扫描失败: ' + err.errMsg);
          }
        });
      });
    },
    async getWxConfig() {
      const url = window.location.href.split('#')[0];
      plantAPI.wxSign({
        url
      }).then(res => {
        wx.config({
          debug: false,
          appId: "wxf6b22350d8075054",
          timestamp: res.data.timestamp.toString(),
          nonceStr: res.data.nonceStr,
          signature: res.data.signature,
          jsApiList: ['scanQRCode']
        });
        wx.ready(() => {
          console.log('微信JS-SDK配置成功');
        });

        wx.error(err => {
          console.error('微信JS-SDK配置失败:', err);
        });
      })
    },
    // 从 URL 中提取参数（code 和 state）
    getUrlParams() {
      const params = {};
      const search = window.location.search.substring(1); // 去除 ? 号
      if (!search) return params;

      search.split('&').forEach(item => {
        const [key, value] = item.split('=');
        params[key] = decodeURIComponent(value || '');
      });
      return params;
    },

    // 处理微信回调逻辑
    // async handleWechatCallback() {
    //   let data = this.getUrlParams()
    //   plantAPI.wxgetOpenid({
    //     code: data.code
    //   }).then(res => {
    //     localStorage.setItem("openId", res.msg)
    //   })
    // },
    // async handleWechatCallback() {
    //   const params = this.getUrlParams();

    //   if (params.code) {
    //     try {
    //       const res = await plantAPI.wxgetOpenid({ code: params.code });
    //       localStorage.setItem("openId", res.msg);
    //     } catch (error) {
    //       console.error('获取openId失败:', error);
    //       this.checkAndTriggerAuth();
    //     }
    //   } else {
    //     this.checkAndTriggerAuth();
    //   }
    // },
    async handleWechatCallback() {
      try {
        const params = this.getUrlParams();
        const storedOpenId = localStorage.getItem("openId");

        // 如果已有 openid 且没有新的 code，直接返回
        if (storedOpenId && !params.code) return;

        // 如果有 code 就获取 openid
        if (params.code) {
          const res = await plantAPI.wxgetOpenid({ code: params.code });
          localStorage.setItem("openId", res.msg);
        } else if (!storedOpenId) {
          this.triggerWechatAuth();
        }
      } catch (error) {
        console.error('微信授权处理失败:', error);
        if (!localStorage.getItem("openId")) {
          this.triggerWechatAuth();
        }
      }
    },
    checkAndTriggerAuth() {
      const storedOpenId = localStorage.getItem("openId");
      if (!storedOpenId) {
        this.triggerWechatAuth();
      }
    },
    triggerWechatAuth() {
      const appId = 'wxf6b22350d8075054';
      const currentUrl = window.location.href.split('#')[0];
      const redirectUri = encodeURIComponent(currentUrl);
      const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;

      window.location.href = authUrl;
    },
    getCode() {
      // 如果正在倒计时或手机号为空，则不执行
      if (this.countdown > 0 || !this.phonenumber) {
        return;
      }
      loginAPI.getSendVerificationCodeAPI({
        phoneNumber: this.phonenumber
      }).then(res => {

      })
      // 开始倒计时
      this.countdown = 60;
      this.timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(this.timer);
        }
      }, 1000);
    },
    goLogin() {
      this.$router.push({
        path: '/login'
      })
    },
    onSubmit(values) {
      if (!this.agree) {
        this.$toast('请先同意隐私协议');
        return;
      }
      values.publicOpenId = localStorage.getItem("openId")
      loginAPI.postRegisterAPI(values).then(res => {
        if (res.code == 200) {
          Toast.success('注册成功');
          setTimeout(() => {
            this.$router.push({
              path: '/login'
            })
          }, 2000)
        }
      })
    },
  }
}
</script>
<style lang="scss" scoped>
/* 在原有样式基础上添加以下样式 */
.code {
  padding: 0 0 0 10px;
  border-left: 1px solid #D3D3D3;
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #EE473B;
  cursor: pointer;

  &.disabled {
    color: #999;
    cursor: not-allowed;
  }
}
</style>